#!/usr/bin/python
# Trivial RPG Bot
#
# This is a trivial RPG bot to demonstrate some of the cool stuff you can do
# with google talk/xmpp

import bot
import sys
import pickle
import random
import time

def log(*args):
	"Replacement for print, which doesn't deal with unicode well"
	msg=u" ".join(map(unicode,args))
	print msg.encode(sys.getdefaultencoding(),"replace")
	
username='bottest'
domain="gmail.com"
password='this isn''t either'


class RPGBot(bot.Bot):
	def __init__(self,*args):
		bot.Bot.__init__(self,*args)
		try:
			self.db=pickle.load(open("rpg.db","r"))
		except:
			self.db={
				"players" : {},
				"creatures" : {
					"bat" : {
						"hp" : 10,
						"attack" : 10,
					},
					"rat" : {
						"hp" : 5,
						"attack" : 4,
					}
				}
			}

	def save(self):
		pickle.dump(self.db,open("rpg.db","w"))

	def new_player(self,user):
		self.db["players"][unicode(user)]={
			"hp" : 100,
			"attack" : 10,
			"lasttime" : time.time(),
		}

	def cmd_search(self,user,userdata,args):
		"Search for a creature to attack"
		if userdata["hp"]<=0:
			self.msg(user,"You are unconcious, you can't search")
			return
		if userdata.has_key("attacking"):
			self.msg(user,"You are already attacking a "+userdata["attacking"]["name"])
			return
		name=random.choice(self.db["creatures"].keys())
		userdata["attacking"]=self.db["creatures"][name].copy()
		userdata["attacking"]["name"]=name
		self.msg(user,"You find a "+userdata["attacking"]["name"])
		self.db[unicode(user.getStripped())]=userdata

	def cmd_attack(self,user,userdata,args):
		"Attack a creature"
		if userdata["hp"]<=0:
			self.msg(user,"You are unconcious, you can't attack")
			return
		if not userdata.has_key("attacking"):
			self.msg(user,"You haven't found anything to attack yet!")
			return
		damage=int(random.random()*userdata["attack"])
		self.msg(user,"You hit the evil "+userdata["attacking"]["name"]+" for "+str(damage)+" points of damage!")
		userdata["attacking"]["hp"]-=damage
		if userdata["attacking"]["hp"]<=0:
			self.msg(user,"The evil "+userdata["attacking"]["name"]+" is dead")
			del userdata["attacking"]
			self.db[unicode(user.getStripped())]=userdata
			return
		damage=int(random.random()*userdata["attacking"]["attack"])
		self.msg(user,"The %s hits you for %i points of damage!" % (
			userdata["attacking"]["name"],
			damage
		))
		userdata["hp"]-=damage
		if userdata["hp"]<=0:
			self.msg(user,"The %s defeated you!" % (
				userdata["attacking"]["name"]
				))
			del userdata["attacking"]
			return
		self.db[unicode(user.getStripped())]=userdata
		self.msg(user,"You have %i hps, and the %s has %i" %(
			userdata["hp"],
			userdata["attacking"]["name"],
			userdata["attacking"]["hp"]))


	def ev_msg(self,user,msg):
		log(user,":",msg)
		args=msg.split(" ")
		cmd="cmd_%s"%args.pop(0).lower()

		id=user.getStripped()

		if not self.db.has_key(id):
			self.new_player(id)
		userdata=self.db["players"][unicode(id)]

		userdata["hp"]=min(100,userdata["hp"]+(time.time()-userdata["lasttime"])/60)
		userdata["lasttime"]=time.time()

		log(userdata)

		if cmd in dir(self):
			getattr(self,cmd)(user,userdata,args)
			self.save()
		else:
			self.msg(user,"Unknown command, try 'help'")


	def ev_unsubscribe(self,user,msg):
		# User removed us from their list
		# So remove them from ours.
		log(user,"unsubscribing:",msg)
		self.removeUser(user)
		self.rejectUser(user)

	def ev_unsubscribed(self,user,msg):
		# User has forced us to remove them from our list
		log(user,"unsubscribing:",msg)
		self.removeUser(user)
		self.rejectUser(user) # Remove us from their list

	def ev_subscribe(self,user,msg):
		# User added us to their list, so add them to ours
		log(user,"subscribing:",msg)
		self.addUser(user)
		self.acceptUser(user)

me = RPGBot(username,password)

me.connect()
me.setOnline('ConferenceBot v2.0')
	
me.run()
